import { defineConfig, loadEnv } from 'vite'
import { resolve } from 'path'
import getServerConfig from './config/server'
import getCssConfig from './config/css'
import getPluginConfig from './config/plugins'
import getBuildConfig from './config/build'

export default ({ mode }) => {
  const cwd = process.cwd()
  const envDir = resolve(cwd, 'config/env')
  const env = loadEnv(mode, envDir)
  const logLevel = mode === 'production' ? 'error' : 'info'
  const notProd = mode !== 'production'

  return defineConfig({
    base: env.VITE_BASE_URL,
    envDir,
    logLevel,
    resolve: {
      alias: {
        '@': resolve(cwd, 'src'),
      },
    },
    esbuild: {
      jsxFactory: 'h',
      jsxFragment: 'Fragment',
      drop: notProd ? [] : ['console', 'debugger'],
    },
    css: getCssConfig(),
    server: getServerConfig({ env }),
    preview: getServerConfig({ env }),
    build: getBuildConfig({ resolve, cwd }),
    plugins: getPluginConfig({ cwd, notProd }),
  })
}
